package com.study.config;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author zhuzi
 * 2023/8/11 14:59
 */
@Slf4j
@org.springframework.web.bind.annotation.ControllerAdvice
public class ControllerAdvice {
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public String handleEx(BindException e) {
        List<FieldError> fieldErrors = e.getFieldErrors();
        return fieldErrors.stream().map(fe -> {
            return StrUtil.format("属性:{} 校验不通过,原因:{}\n", fe.getField(), fe.getDefaultMessage());
        }).collect(Collectors.joining(","));
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public String handleExMethod(ConstraintViolationException e) {
        log.info("Const...校验失败");
        Set<ConstraintViolation<?>> fieldErrors = e.getConstraintViolations();
        return fieldErrors.stream().map(fe -> {
            return StrUtil.format("属性:{} 值{} 校验不通过,原因:{}\n", fe.getPropertyPath(), fe.getInvalidValue(), fe.getMessage());
        }).collect(Collectors.joining(","));
    }
}
